<template>
  <div class="app-container">
    <el-row>
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :inline="true" v-show="showSearch" label-width="170px" :label-position="isPhone ? 'top' : 'left'">
          <el-form-item label="学生姓名">
            <el-input
              v-model="queryParams.studentName"
              placeholder="请输入学生姓名"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="企业导师姓名">
            <el-input
              v-model="queryParams.entTeacherName"
              placeholder="请输入企业导师姓名"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="企业导师单位">
            <el-input
              v-model="queryParams.entTeacherDept"
              placeholder="请输入企业导师单位"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="企业导师助理姓名">
            <el-input
              v-model="queryParams.entAssistantName"
              placeholder="请输入企业导师助理姓名"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="企业导师助理单位">
            <el-input
              v-model="queryParams.entAssistantDept"
              placeholder="请输入企业导师助理单位"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="培养部门管理员姓名">
            <el-input
              v-model="queryParams.trainOrgName"
              placeholder="请输入培养部门管理员姓名"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="培养部门管理员职务">
            <el-input
              v-model="queryParams.trainOrgPosition"
              placeholder="请输入培养部门管理员职务"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="培养单位管理员姓名">
            <el-input
              v-model="queryParams.trainDepName"
              placeholder="请输入培养单位管理员姓名"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="培养单位管理员职务">
            <el-input
              v-model="queryParams.trainDepPosition"
              placeholder="请输入培养单位管理员职务"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasRole="[
                'admin',
                'enterprise_depart_admin',
                'enterprise_unit_admin',
                'enterprise_teacher',
                'enterprise_agreement',
              ]"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              :loading="exportLoading"
              :disabled="exportLoading"
              v-hasPermi="['system:user:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="handleGetList"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="list"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="学生姓名"
            align="center"
            key="nickName"
            prop="nickName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="学生账号"
            align="center"
            key="userName"
            prop="userName"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="企业导师姓名"
            align="center"
            key="entTeacherName"
            prop="trainEntTeacherUser.nickName"
            v-if="columns[3].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="企业导师单位"
            align="center"
            key="entTeacherDept"
            prop="trainEntTeacherUser.deptName"
            v-if="columns[4].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="企业导师联系电话"
            align="center"
            key="entTeacherPhone"
            prop="trainEntTeacherUser.phonenumber"
            v-if="columns[5].visible"
            width="140"
          />
          <el-table-column
            label="企业导师助理姓名"
            align="center"
            key="entAssistantName"
            prop="trainEntAssistantUser.nickName"
            v-if="columns[6].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="企业导师助理单位"
            align="center"
            key="entAssistantDept"
            prop="trainEntAssistantUser.deptName"
            v-if="columns[7].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="企业导师助理联系电话"
            align="center"
            key="entAssistantPhone"
            prop="trainEntAssistantUser.phonenumber"
            v-if="columns[8].visible"
            width="150"
          />
          <el-table-column
            label="培养部门管理员姓名"
            align="center"
            key="trainOrgName"
            prop="trainOrgUser.nickName"
            v-if="columns[9].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="培养部门管理员职务"
            align="center"
            key="trainOrgPosition"
            prop="trainOrgUser.position"
            v-if="columns[10].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="培养部门管理员联系电话"
            align="center"
            key="trainOrgPhone"
            prop="trainOrgUser.phonenumber"
            v-if="columns[11].visible"
            width="160"
          />
          <el-table-column
            label="培养单位管理员姓名"
            align="center"
            key="trainDepName"
            prop="trainDepUser.nickName"
            v-if="columns[12].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="培养单位管理员职务"
            align="center"
            key="trainDepPosition"
            prop="trainDepUser.position"
            v-if="columns[13].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="培养单位管理员联系电话"
            align="center"
            key="trainDepPhone"
            prop="trainDepUser.phonenumber"
            v-if="columns[14].visible"
            width="160"
          />
          <el-table-column
            label="操作"
            align="center"
            width="150"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="详情" placement="top">
                <el-button
                  link
                  type="info"
                  icon="View"
                  @click="handleDetail(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="修改" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                  v-hasRole="
                    scope.row.approvalStatus === 'approved'
                      ? ['admin', 'enterprise_group_admin']
                      : [
                          'admin',
                          'enterprise_depart_admin',
                          'enterprise_unit_admin',
                          'enterprise_teacher',
                          'enterprise_agreement',
                        ]
                  "
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasRole="['admin', 'enterprise_group_admin']"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                content="提交"
                placement="top"
                v-if="
                  scope.row.approvalStatus === 'no_submit' ||
                  scope.row.approvalStatus === 'rejected'
                "
              >
                <el-button
                  link
                  type="warning"
                  icon="Upload"
                  @click="handleSubmit(scope.row)"
                  :loading="submitApprovalLoading"
                  :disabled="submitApprovalLoading"
                  v-hasRole="[
                    'admin',
                    'enterprise_depart_admin',
                    'enterprise_unit_admin',
                    'enterprise_teacher',
                    'enterprise_agreement',
                  ]"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                content="审批"
                placement="top"
                v-if="scope.row.approvalAuth"
              >
                <el-button
                  link
                  type="success"
                  icon="Check"
                  @click="handleApprove(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleGetList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="140px" :label-position="isPhone ? 'top' : 'left'">
        <el-row>
          <el-col :span="24">
            <el-form-item label="学生" prop="userId">
              <el-select
                v-model="form.userId"
                placeholder="请选择学生"
                clearable
                style="width: 100%"
                :disabled="title === '查看企业导师详情'"
                @change="handleStudentChange"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="企业导师" prop="trainEntTeacherUserId">
              <el-select
                v-model="form.trainEntTeacherUserId"
                placeholder="请选择企业导师"
                clearable
                style="width: 100%"
                :disabled="title === '查看企业导师详情'"
                @change="handleEntTeacherChange"
              >
                <el-option
                  v-for="item in trainEntTeacherUserList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="selectedEntTeacher">
            <el-form-item label="单位">
              <el-input
                v-model="selectedEntTeacher.deptName"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="selectedEntTeacher">
            <el-form-item label="职务">
              <el-input
                v-model="selectedEntTeacher.position"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="selectedEntTeacher">
            <el-form-item label="职称">
              <el-input
                :value="selectDictLabel(professional_title, selectedEntTeacher.rank)"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="selectedEntTeacher">
            <el-form-item label="学历">
              <el-input
                :value="selectDictLabel(educational_qualifications, selectedEntTeacher.qualification)"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="selectedEntTeacher">
            <el-form-item label="联系电话">
              <el-input
                v-model="selectedEntTeacher.phonenumber"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="企业导师助理" prop="trainEntAssistantUserId">
              <el-select
                v-model="form.trainEntAssistantUserId"
                placeholder="请选择企业导师助理"
                clearable
                style="width: 100%"
                :disabled="title === '查看企业导师详情'"
                @change="handleEntAssistantChange"
              >
                <el-option
                  v-for="item in trainEntAssistantUserList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 企业导师助理详细信息展示 -->
          <el-col :span="8" v-if="selectedEntAssistant">
            <el-form-item label="单位">
              <el-input
                v-model="selectedEntAssistant.deptName"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="selectedEntAssistant">
            <el-form-item label="职务">
              <el-input
                v-model="selectedEntAssistant.position"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="selectedEntAssistant">
            <el-form-item label="职称">
              <el-input
                :value="selectDictLabel(professional_title, selectedEntAssistant.rank)"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="selectedEntAssistant">
            <el-form-item label="学历">
              <el-input
                :value="selectDictLabel(educational_qualifications, selectedEntAssistant.qualification)"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="selectedEntAssistant">
            <el-form-item label="联系电话">
              <el-input
                v-model="selectedEntAssistant.phonenumber"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="selectedStudent?.practiceDeptId">
            <el-form-item label="培养部门管理员" prop="trainOrgUserId">
              <el-select
                v-model="form.trainOrgUserId"
                placeholder="请选择培养部门管理员"
                clearable
                style="width: 100%"
                :disabled="title === '查看企业导师详情'"
                @change="handleTrainOrgChange"
              >
                <el-option
                  v-for="item in trainOrgUserList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 培养部门管理员详细信息展示 -->
          <el-col :span="8" v-if="selectedTrainOrg">
            <el-form-item label="职务">
              <el-input
                v-model="selectedTrainOrg.position"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="selectedTrainOrg">
            <el-form-item label="联系电话">
              <el-input
                v-model="selectedTrainOrg.phonenumber"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="培养单位管理员" prop="trainDepUserId">
              <el-select
                v-model="form.trainDepUserId"
                placeholder="请选择培养单位管理员"
                clearable
                style="width: 100%"
                :disabled="title === '查看企业导师详情'"
                @change="handleTrainDepChange"
              >
                <el-option
                  v-for="item in trainDepUserList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 培养单位管理员详细信息展示 -->
          <el-col :span="8" v-if="selectedTrainDep">
            <el-form-item label="职务">
              <el-input
                v-model="selectedTrainDep.position"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="selectedTrainDep">
            <el-form-item label="联系电话">
              <el-input
                v-model="selectedTrainDep.phonenumber"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form-item
        label="审核意见"
        prop="approvalRemark"
        style="margin-bottom: 0"
        v-if="form.approvalStatus === 'rejected'"
      >
        <el-input
          v-model="form.approvalRemark"
          disabled
          type="textarea"
          placeholder="请输入审核意见"
          :rows="3"
          style="width: 100%"
        ></el-input>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <!-- 审批模式下的审核意见字段 -->
          <div v-if="title === '审批企业导师'" style="margin-bottom: 20px">
            <el-form-item
              label="审核意见"
              prop="approvalRemark"
              style="margin-bottom: 0"
            >
              <el-input
                v-model="form.approvalRemark"
                type="textarea"
                placeholder="请输入审核意见"
                :rows="3"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </div>

          <!-- 普通编辑模式按钮 -->
          <template v-if="title !== '审批企业导师' && title !== '查看企业导师详情'">
            <el-button 
              type="primary" 
              @click="submitForm"
              :loading="submitLoading"
              :disabled="submitLoading"
            >确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </template>

          <!-- 详情模式按钮 -->
          <template v-if="title === '查看企业导师详情'">
            <el-button @click="cancel">关 闭</el-button>
          </template>

          <!-- 审批模式按钮 -->
          <template v-else>
            <el-button 
              type="success" 
              @click="handleApprovePass"
              :loading="approvePassLoading"
              :disabled="approvePassLoading"
              >通 过</el-button
            >
            <el-button 
              type="danger" 
              @click="handleApproveReject"
              :loading="approveRejectLoading"
              :disabled="approveRejectLoading"
              >驳 回</el-button
            >
            <el-button @click="cancel">取 消</el-button>
          </template>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CorporateMentor">
import {
  getList,
  addItem,
  editItem,
  delItem,
  getDetail,
} from "@/api/corporate-mentor";
import { submitApproval, handleApproval } from "@/api/approval";
import { getStudentList, getTeacherList } from "@/api/common";
import { selectDictLabel } from "@/utils/ruoyi";
import { isPhone } from "@/utils/index";

const router = useRouter();
const { proxy } = getCurrentInstance();
const { professional_title, educational_qualifications } = proxy.useDict("professional_title", "educational_qualifications");

const list = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 列显隐信息
const columns = ref([
  { key: 0, label: `编号`, visible: true },
  { key: 2, label: `姓名`, visible: true },
  { key: 1, label: `账号`, visible: true },
  { key: 4, label: `企业导师姓名`, visible: true },
  { key: 5, label: `企业导师单位`, visible: true },
  { key: 6, label: `企业导师联系电话`, visible: true },
  { key: 7, label: `企业导师助理姓名`, visible: true },
  { key: 8, label: `企业导师助理单位`, visible: true },
  { key: 9, label: `企业导师助理联系电话`, visible: true },
  { key: 10, label: `培养部门管理员姓名`, visible: true },
  { key: 11, label: `培养部门管理员职务`, visible: true },
  { key: 12, label: `培养部门管理员联系电话`, visible: true },
  { key: 13, label: `培养单位管理员姓名`, visible: true },
  { key: 14, label: `培养单位管理员职务`, visible: true },
  { key: 15, label: `培养单位管理员联系电话`, visible: true },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentName: undefined,
    entTeacherName: undefined,
    entTeacherDept: undefined,
    entAssistantName: undefined,
    entAssistantDept: undefined,
    trainOrgName: undefined,
    trainOrgPosition: undefined,
    trainDepName: undefined,
    trainDepPosition: undefined,
  },
  rules: {
    userId: [{ required: true, message: "请选择学生", trigger: "change" }],
    trainEntTeacherUserId: [
      { required: true, message: "请选择企业导师", trigger: "change" },
    ],
    trainEntAssistantUserId: [
      { required: true, message: "请选择企业导师助理", trigger: "change" },
    ],
    trainOrgUserId: [
      { required: true, message: "请选择培养部门管理员", trigger: "change" },
    ],
    trainDepUserId: [
      { required: true, message: "请选择培养单位管理员", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

const userList = ref([]);
const trainEntTeacherUserList = ref([]);
const trainEntAssistantUserList = ref([]);
const trainOrgUserList = ref([]);
const trainDepUserList = ref([]);

// 按钮loading状态
const submitLoading = ref(false);
const approvePassLoading = ref(false);
const approveRejectLoading = ref(false);
const submitApprovalLoading = ref(false);
const exportLoading = ref(false);
const selectedEntTeacher = ref(null);
const selectedEntAssistant = ref(null);
const selectedTrainOrg = ref(null);
const selectedTrainDep = ref(null);

/** 查询用户列表 */
function handleGetList() {
  loading.value = true;
  getList(queryParams.value).then((res) => {
    loading.value = false;
    list.value = res.rows;
    total.value = res.total;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  handleGetList();
}
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    studentName: undefined,
    entTeacherName: undefined,
    entTeacherDept: undefined,
    entAssistantName: undefined,
    entAssistantDept: undefined,
    trainOrgName: undefined,
    trainOrgPosition: undefined,
    trainDepName: undefined,
    trainDepPosition: undefined,
  };
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除编号为"' + id + '"的数据项？')
    .then(function () {
      return delItem(id);
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  exportLoading.value = true;
  try {
    proxy.download(
      "system/user/export",
      {
        ...queryParams.value,
      },
      `user_${new Date().getTime()}.xlsx`
    );
  } finally {
    // 设置延迟，确保用户能看到loading效果
    setTimeout(() => {
      exportLoading.value = false;
    }, 1000);
  }
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    trainEntTeacherUserId: undefined,
    trainEntAssistantUserId: undefined,
    trainOrgUserId: undefined,
    trainDepUserId: undefined,
    approvalRemark: undefined,
  };
  selectedEntTeacher.value = null;
  selectedEntAssistant.value = null;
  selectedTrainOrg.value = null;
  selectedTrainDep.value = null;
  proxy.resetForm("formRef");
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加企业导师";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getDetail(id).then((response) => {
    form.value = response.data;
    handleStudentChange(row.userId);
    open.value = true;
    title.value = "修改企业导师";
  });
}
/** 提交按钮 */
function submitForm() {
  // 防止重复提交
  if (submitLoading.value) return;
  
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      submitLoading.value = true;
      
      if (form.value.id != undefined) {
        editItem(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          handleGetList();
        }).finally(() => {
          submitLoading.value = false;
        });
      } else {
        addItem(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          handleGetList();
        }).finally(() => {
          submitLoading.value = false;
        });
      }
    }
  });
}

// 提交审核
function handleSubmit(row) {
  // 防止重复提交
  if (submitApprovalLoading.value) return;
  
  const id = row.id || ids.value;
  const item = list.value.find(item => item.id === id);
  proxy.$modal
    .confirm("是否确认提交审核？")
    .then(function () {
      submitApprovalLoading.value = true;
      return submitApproval({
        businessId: id,
        approvalTypeCode: "student_ent_teacher_flow",
        approvalInfo: JSON.stringify(item)
      });
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("提交成功");
    })
    .catch(() => {})
    .finally(() => {
      submitApprovalLoading.value = false;
    });
}

// 审批操作
function handleApprove(row) {
  reset();
  const id = row.id || ids.value;
  getDetail(id).then((response) => {
    form.value = {
      ...response.data,
      approvalRemark: "",
    };
    handleStudentChange(response.data.userId);
    open.value = true;
    title.value = "审批企业导师";
  });
}

// 通过审批
function handleApprovePass() {
  // 防止重复提交
  if (approvePassLoading.value) return;
  
  approvePassLoading.value = true;
  const approvalData = {
    approvalInfoId: form.value.approvalInfoId,
    approvalNodeId: form.value.approvalNodeId,
    approvalStatus: "approved",
    remark: form.value.approvalRemark,
  };

  handleApproval(approvalData).then(() => {
    proxy.$modal.msgSuccess("审批通过");
    open.value = false;
    handleGetList();
  }).finally(() => {
    approvePassLoading.value = false;
  });
}

// 驳回审批
function handleApproveReject() {
  if (!form.value.approvalRemark) {
    proxy.$modal.msgError("请填写审核意见");
    return;
  }

  // 防止重复提交
  if (approveRejectLoading.value) return;

  approveRejectLoading.value = true;
  const approvalData = {
    approvalInfoId: form.value.approvalInfoId,
    approvalNodeId: form.value.approvalNodeId,
    approvalStatus: "rejected",
    remark: form.value.approvalRemark,
  };

  handleApproval(approvalData).then(() => {
    proxy.$modal.msgSuccess("已驳回");
    open.value = false;
    handleGetList();
  }).finally(() => {
    approveRejectLoading.value = false;
  });
}

// 详情操作
function handleDetail(row) {
  reset();
  const id = row.id || ids.value;
  getDetail(id).then((response) => {
    form.value = response.data;
    handleStudentChange(row.userId);
    open.value = true;
    title.value = "查看企业导师详情";
  });
}

const selectedStudent = ref(null);
function handleStudentChange(userId) {
  selectedStudent.value = userList.value.find((user) => user.userId === userId) || null;
  getTeacherList({ userId: userId, roleKey: "enterprise_teacher" }).then(
    (res) => {
      trainEntTeacherUserList.value = res.data;
      // 如果表单中已有企业导师ID，设置选中的企业导师信息
      if (form.value.trainEntTeacherUserId) {
        setTimeout(() => {
          handleEntTeacherChange(form.value.trainEntTeacherUserId);
        }, 50);
      }
    }
  );
  getTeacherList({ userId: userId, roleKey: "enterprise_agreement" }).then(
    (res) => {
      trainEntAssistantUserList.value = res.data;
      // 如果表单中已有企业导师助理ID，设置选中的企业导师助理信息
      if (form.value.trainEntAssistantUserId) {
        setTimeout(() => {
          handleEntAssistantChange(form.value.trainEntAssistantUserId);
        }, 50);
      }
    }
  );
  getTeacherList({ userId: userId, roleKey: "enterprise_depart_admin" }).then(
    (res) => {
      trainOrgUserList.value = res.data;
      // 如果表单中已有培养部门管理员ID，设置选中的培养部门管理员信息
      if (form.value.trainOrgUserId) {
        setTimeout(() => {
          handleTrainOrgChange(form.value.trainOrgUserId);
        }, 50);
      }
    }
  );
  getTeacherList({ userId: userId, roleKey: "enterprise_unit_admin" }).then(
    (res) => {
      trainDepUserList.value = res.data;
      // 如果表单中已有培养单位管理员ID，设置选中的培养单位管理员信息
      if (form.value.trainDepUserId) {
        setTimeout(() => {
          handleTrainDepChange(form.value.trainDepUserId);
        }, 50);
      }
    }
  );
}

// 处理企业导师选择变更
function handleEntTeacherChange(userId) {
  if (userId) {
    // 从企业导师列表中找到选中的导师信息
    selectedEntTeacher.value =
      trainEntTeacherUserList.value.find(
        (teacher) => teacher.userId === userId
      ) || null;
  } else {
    selectedEntTeacher.value = null;
  }
}

// 处理企业导师助理选择变更
function handleEntAssistantChange(userId) {
  if (userId) {
    // 从企业导师助理列表中找到选中的助理信息
    selectedEntAssistant.value =
      trainEntAssistantUserList.value.find(
        (assistant) => assistant.userId === userId
      ) || null;
  } else {
    selectedEntAssistant.value = null;
  }
}

// 处理培养部门管理员选择变更
function handleTrainOrgChange(userId) {
  if (userId) {
    // 从培养部门管理员列表中找到选中的管理员信息
    selectedTrainOrg.value =
      trainOrgUserList.value.find((org) => org.userId === userId) || null;
  } else {
    selectedTrainOrg.value = null;
  }
}

// 处理培养单位管理员选择变更
function handleTrainDepChange(userId) {
  if (userId) {
    // 从培养单位管理员列表中找到选中的管理员信息
    selectedTrainDep.value =
      trainDepUserList.value.find((dep) => dep.userId === userId) || null;
  } else {
    selectedTrainDep.value = null;
  }
}

handleGetList();
getStudentList({ roleKey: "student" }).then((res) => {
  userList.value = res.data;
});
</script>
